package com.github.pig.common.util;

import lombok.Data;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;

import java.io.Serializable;


/**
 * 自定义响应结构
 * @author J神
 * @date 2018/4/26
 **/
@Data
public class ZyResult<T> implements Serializable {

   /** 响
    * 应业务状态
    */
   private Integer status;

    /**
     *      响应消息
     */

   private String message;

    /**
     * 响应中的数据
     */
   private T data;

   private Long timestamp=System.currentTimeMillis();

   private String error="";

   private String exception="";


   public ZyResult() {

   }

   public ZyResult(Integer status, String message, T data, String error, String exception) {
       this.status = status;
       this.message = message;
       this.data = data;
       this.error=error;
       this.exception=exception;
   }
    public ZyResult(Integer status, String message, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }
   public ZyResult(T data) {
       this.status = HttpStatus.OK.value();
       this.message = HttpStatus.OK.getReasonPhrase();
       this.data = data;
   }

   public static ZyResult validError(BindingResult result) {
       return ZyResult.build(HttpStatus.BAD_REQUEST.value(),
               result.getFieldError().getDefaultMessage(), result.getFieldErrors());
   }
    public static ZyResult build(Integer status, String message, Object data) {
        return new ZyResult(status, message, data);
    }
    public static ZyResult build(HttpStatus status, Object data) {
        return new ZyResult(status.value(), status.getReasonPhrase(), data);
    }
    public static ZyResult error(HttpStatus status, String message, String error, String exception, Object data){
           return new ZyResult(status.value(),message,data,error,exception);
    }
    public static ZyResult error(){
        return new ZyResult(HttpStatus.INTERNAL_SERVER_ERROR.value(),"",null,HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"");
    }
    public static ZyResult error(Exception e) {
        return new ZyResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), "", null, HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e.getMessage());
    }
    public static ZyResult ok(Object data) {
        return new ZyResult(data);
    }
    public static ZyResult ok() {
        return new ZyResult(null);
    }
}
